package com.sun.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;

/**
 * @Author Sun
 * @Date 2020/4/20 21:03
 * @Version 1.0
 */
/*
    解决cookie的value为中文乱码的问题
    创建cookie的vlaue的时候进行编码：  Cookie cookie = new Cookie("name", URLEncoder.encode("孙炳锐", "utf-8"));
    输出value的时候进行解码：        writer.write(URLDecoder.decode(cookie.getValue(), "utf-8"));
 */
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //解决请求页面和响应页面的乱码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        Cookie[] cookies = req.getCookies();//从请求中拿到多个cookies

        //判断是否有cookie
        if(cookies != null){
            writer.write("上次登陆时间：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的key
                if(cookie.getName().equals("LastLoginTime")){
                    long LastLoginTime = Long.parseLong(cookie.getValue());//获取cookie的value，将字符串类型的时间戳转换成long型
                    Date date = new Date(LastLoginTime);//把时间戳转换成日期类型
                    writer.write(date.toLocaleString());//将日期类型转换成字符串输出
                }
            }
        }else {
           writer.print("这是第一次登陆！");
        }

        //cookie对象通过key-value形式存在，并且value只能是String类型
        Cookie cookie = new Cookie("LastLoginTime", System.currentTimeMillis()+"");
        //cookie.setMaxAge(24*60*60);//设置cookie的有效期为一天
        resp.addCookie(cookie);//服务端响应给客户端一个cookie

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
